<?php

namespace app\queue\stomp;

use app\queue\BaseConsumer;
use support\bootstrap\Redis;
use common\service\EventLogService;

class EventConsumer extends BaseConsumer
{

    // 要消费的队列名
    public $queue = 'event';

    // 连接名，对应 config/redis_queue.php 里的连接`
    public $connection = 'default';

    /**
     * 处理事件
     * @param $data
     */
    public function doConsume($data)
    {
        $key = $data['event_data_key'];
        // 2021年6月4日 禁用event_log写入
//        Redis::del($key);
//        return;
        // 记录 Event log 数据
        $eventLogService = new EventLogService();

        $records = [];
        $index = 0;
        while (Redis::lLen($key) > 0) {

            $r = Redis::lPop($key);
            if (!empty($r)) {
                $records[] = json_decode($r, true);
            }

            // 分片执行 避免内存不够
            if (count($records) >= 100 || (Redis::lLen($key) == 0 && count($records) > 0)) {
                try {
                    $eventLogService->create($records);
                } catch (\Throwable $e) {
                    trace($e->getCode(), "ERR");
                    trace($e->getMessage(), "ERR");
                    trace($e->getTraceAsString(), "ERR");
                }
                $index += count($records);
                $records = [];
            }
        }

    }
}
